package com.thread.sync.sync03;

public class DoubleCheckSingleton {
    private static DoubleCheckSingleton ds;

    //单例模式
    public static DoubleCheckSingleton getDs() {
        if (ds == null) {
            //模拟极端情况
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (DoubleCheckSingleton.class) {
                //双重判断,防止极端情况,多个线程都进入了第一个if,
                if (ds == null) {
                    ds = new DoubleCheckSingleton();
                }
            }
        }
        return ds;
    }

    public static void main(String[] args) {
        //打印hashcode.如果一样,则表示为单例
        new Thread(() -> {
            System.out.println(getDs().hashCode());
        }).start();
        new Thread(() -> {
            System.out.println(getDs().hashCode());
        }).start();
        new Thread(() -> {
            System.out.println(getDs().hashCode());
        }).start();
    }

}
